package lily.phs.vaccination;

import java.util.ArrayList;
import java.util.Calendar;


import lily.phs.object.HealthTest;
import lily.phs.object.HereTipa;
import lily.phs.object.HospitalHistory;
import lily.phs.object.HuiZhenRecord;
import lily.phs.object.JieZhenRecord;
import lily.phs.object.MedicateRecord;
import lily.phs.object.ModuleSelect;
import lily.phs.object.NonimmuneVaccineHistory;
import lily.phs.object.PersonInfo;
import lily.phs.object.SickbedHistory;
import lily.phs.object.VaccinationCard;
import lily.phs.object.VaccinationRecord;
import lily.phs.urh.PeopleList;
import lily.phs.urh.R;
import lily.phs.urh.PeopleList.myThread;
import lily.phs.child.ImageList;
import lily.phs.database.Constants;
import lily.ui.bookshelf.CaseLevelView;
import lily.ui.bookshelf.ProfileView;
import lily.ui.bookshelf.WindowSizeUtil;
import lily.ui.control.MyPopupWindow;
import lily.ui.control.SearchPopupWindow;
import lily.ui.panel.Panel;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class VaccinationActivity extends Activity implements OnClickListener,Constants,OnFocusChangeListener{
	private static final String[] PROJECTION = new String[]{ 
		VACA_PROFILE_ID/*卡片ID*/, 
		};
	private View view;
	private ArrayList<CaseLevelView> AllLevels;
	private LinearLayout ll_Content;
	private int ProfilesSUM;//档案总数
	private int ProfilesInOneLevel;//每层最多可放置的档案数
	private String[] allProfiles;
	private ProgressDialog mpDialog;
	 AlertDialog ad;
	 MyPopupWindow mPopupWindow;
	private int idList[];
	//private EditText et_name,et_sex,et_born,et_guardian_name,et_relation,et_guardian_phone,et_create_people,et_create_date;
	 EditText et_id,et_name,et_nowplace,et_hjdz,et_tel,et_xzname,et_cwhname,et_jddw,et_jdr,et_doctor,et_date;
	private SearchPopupWindow sPopupWindow;
	private Button leftBtn,rightBtn2,rightBtn;
	private Panel panel;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		LayoutInflater factory=(LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		view=factory.inflate(R.layout.profilecase, null);
		final TextView tvTitle = (TextView)view.findViewById(R.id.title);
		tvTitle.setText("预防接种");
		
		panel = (Panel)view.findViewById(R.id.bottompanel);
		
		ll_Content=(LinearLayout)view.findViewById(R.id.shelves_content);
		AllLevels=new ArrayList<CaseLevelView>();
		addNewLevel();
		addNewLevel();
		addNewLevel();
		addNewLevel();
		addNewLevel();
		addNewLevel();
		
		
		mpDialog=new ProgressDialog(VaccinationActivity.this);
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		mpDialog.setMessage("正在加载···");
		mpDialog.setIndeterminate(false);
		mpDialog.setCancelable(true);
		mpDialog.show();
		new myThread(handler,"",1).start();
		
		GridView grid = (GridView)this.findViewById(R.id.bottomgrid);
		String[] menus = new String[]{"添加","刷新","查询"};
		int[] images = new int[]{R.drawable.add_files,R.drawable.fresh,R.drawable.search_file};
		ImageList adapter = new ImageList(this,images,menus);
		grid.setAdapter(adapter);
		
		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				panel.setOpen(false, false);
				
				switch (arg2) {
				case 0:				
					LayoutInflater factory = LayoutInflater.from(getBaseContext());
		            final View textEntryView = factory.inflate(R.layout.build_new_profile, null);
		            et_date=(EditText)textEntryView.findViewById(R.id.et_jmjkda_date);
		            et_date.setInputType(InputType.TYPE_NULL);
		            et_date.setOnFocusChangeListener(new OnFocusChangeListener() {
						
						@Override
						public void onFocusChange(View v, boolean hasFocus) {
							// TODO Auto-generated method stub
							if(v==et_date&&hasFocus){
								mPopupWindow = new MyPopupWindow(getBaseContext());			
								mPopupWindow.showAtLocation((textEntryView.findViewById(R.id.et_jmjkda_date)), Gravity.CENTER, 0, 0);

								Button btn=mPopupWindow.getButton();
								btn.setOnClickListener(new OnClickListener(){

									@Override
									public void onClick(View v) {
										// TODO Auto-generated method stub
										et_date.setText(mPopupWindow.getDate());
										mPopupWindow.dismiss();
									}
									
								});
							}
						}
					});
				
		            et_date.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							mPopupWindow = new MyPopupWindow(getBaseContext());			
							mPopupWindow.showAtLocation(textEntryView.findViewById(R.id.et_jmjkda_date), Gravity.CENTER, 0, 0);

							Button btn=mPopupWindow.getButton();
							btn.setOnClickListener(new OnClickListener(){

								@Override
								public void onClick(View v) {
									// TODO Auto-generated method stub
									et_date.setText(mPopupWindow.getDate());
									mPopupWindow.dismiss();
								}
								
							});
						}
		            	
		            });
		            
						
				
		            ad=new AlertDialog.Builder(VaccinationActivity.this)
		                .setIcon(R.drawable.add_profile)
		                .setTitle("新建档案")
		                .setView(textEntryView).create();
		            ad.show();
		               
		            
		            Button bt_ok=(Button)textEntryView.findViewById(R.id.bt_jmjkda_ok);
		            Button bt_cancle=(Button)textEntryView.findViewById(R.id.bt_jmjkda_cancle);
		                bt_ok.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View v) {
								// TODO Auto-generated method stub
								et_id=(EditText)textEntryView.findViewById(R.id.et_jmjkda_id);
					            et_name=(EditText)textEntryView.findViewById(R.id.et_jmjkda_name);
					            et_nowplace=(EditText)textEntryView.findViewById(R.id.et_jmjkda_nowplace);
					            et_hjdz=(EditText)textEntryView.findViewById(R.id.et_jmjkda_hjdz);
					            et_tel=(EditText)textEntryView.findViewById(R.id.et_jmjkda_tel);
					            et_xzname=(EditText)textEntryView.findViewById(R.id.et_jmjkda_xzname);
					            et_cwhname=(EditText)textEntryView.findViewById(R.id.et_jmjkda_cwhname);
					            et_jddw=(EditText)textEntryView.findViewById(R.id.et_jmjkda_jddw);
					            et_jdr=(EditText)textEntryView.findViewById(R.id.et_jmjkda_jdr);
					            et_doctor=(EditText)textEntryView.findViewById(R.id.et_jmjkda_doctor);
					            
								if(et_name.getText().toString().length()<1){
									et_name.setError("姓名不能为空!");
								}
								else if(et_id.getText().toString().length()<1){
									et_id.setError("编号不能为空!");
								}
								
								
								else{
									mpDialog = new ProgressDialog(VaccinationActivity.this);  
									mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
									mpDialog.setMessage("正在新建档案...");  
									mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
									mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
									mpDialog.show();
									new myThread(handler,"",11).start();
									
								}
							}
		                	
		                });
		                
		                bt_cancle.setOnClickListener(new OnClickListener(){

							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								ad.cancel();
							}
		                	
		                });
		                
		                   
		                break;
					
				case 1:
					mpDialog = new ProgressDialog(VaccinationActivity.this);  
					mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
					mpDialog.setMessage("正在加载...");  
					mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
					mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
					mpDialog.show();
					new myThread(handler,"",2).start();
					break;
				case 2:
					
					sPopupWindow = new SearchPopupWindow(getBaseContext());		
					sPopupWindow.showAtLocation(findViewById(R.id.title_left_btn), Gravity.CENTER, 0, 0);
					sPopupWindow.setAnimationStyle(R.anim.i_slide_in_left);
					final Button bt=sPopupWindow.getBt();
					final EditText et=sPopupWindow.getEt();
					bt.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							//searchContentView(et.getText().toString());
							mpDialog = new ProgressDialog(VaccinationActivity.this);  
							mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//设置风格为圆形进度条  
							mpDialog.setMessage("正在刷新...");  
							mpDialog.setIndeterminate(false);//设置进度条是否为不明确  
							mpDialog.setCancelable(true);//设置进度条是否可以按退回键取消  
							mpDialog.show();
							new myThread(handler,et.getText().toString(),1).start();
						}
						
					});
				default:
					break;
				}
			}

		});
		leftBtn = (Button) findViewById(R.id.title_left_btn);
        rightBtn = (Button) findViewById(R.id.title_right_btn);
        rightBtn2 = (Button) findViewById(R.id.title_right_btn2);
        leftBtn.setText("后退");
        rightBtn.setVisibility(View.INVISIBLE);
        rightBtn2.setVisibility(View.INVISIBLE);
        leftBtn.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.anim_slide_in_left,R.anim.anim_slide_out_right);
			}
        	
        });
	}
	private void addNewLevel() {
		// TODO Auto-generated method stub
		CaseLevelView newcaseLevelView = new CaseLevelView(this);
		AllLevels.add(newcaseLevelView);
		ll_Content.addView(
				newcaseLevelView,newcaseLevelView.LevelWidth,newcaseLevelView.LevelHeight);//
//				MeasureSpec.makeMeasureSpec(newcaseLevelView.LevelWidth, MeasureSpec.EXACTLY),
//				MeasureSpec.makeMeasureSpec(newcaseLevelView.LevelHeight, MeasureSpec.EXACTLY));
//		Log.i(TAG, ""+MeasureSpec.makeMeasureSpec(newcaseLevelView.LevelWidth, MeasureSpec.EXACTLY));
		System.out.println("addLevel:"+newcaseLevelView.LevelWidth+","+newcaseLevelView.LevelHeight);
		setContentView(view);
		
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
	//	int i=v.getId();
		Intent editprofile = new Intent();
		Bundle bd = new Bundle();
		bd.putInt("Profile_id", v.getId());//待编辑档案的ID
		bd.putInt("father", MODULE_FATHER);
		bd.putInt("call", MODULE_LIST);
		editprofile.putExtras(bd);
		editprofile.setClass(VaccinationActivity.this, VaccinationScrollActivity.class);
		startActivity(editprofile);
		overridePendingTransition(R.anim.anim_slide_in_right,R.anim.anim_slide_out_left);
		
	}
	
	/******************************************************************/
	/**
	 * @return 每一层可放的档案数
	 */
    private int getProfilesInOneLevel() {
    	// TODO Auto-generated method stub
		
    	WindowSizeUtil util = new WindowSizeUtil(this);
		ProfileView newProfile = new ProfileView(this);
		return util.ScreenWidth/newProfile.FileWidth;
		
    }
    
    private void searchContentView(String name, int state) {
		// TODO Auto-generated method stub
    	Cursor cursor;
		name.replace(" ", "");
		if(state==1){
		cursor = this.managedQuery(CONTENT_URI_VIEW3,null, 
				HETI_NAME+" LIKE '%"+name+"%'", null, null);
		}
		else {
			cursor = this.managedQuery(CONTENT_URI_VIEW3,null, 
					null, null, null);
		}
		ProfilesSUM = cursor.getCount();
		//ProfilesInOneLevel = getProfilesInOneLevel();//计算每层可以存放的档案数
        System.out.println("ProfilesInOneLevel="+ProfilesInOneLevel);
        
		allProfiles = new String[ProfilesSUM];
        idList=new int[ProfilesSUM];
        for(int i=0;i<allProfiles.length;i++){
        	cursor.moveToNext();
        	int ID = cursor.getInt(0);
        	idList[i]=cursor.getInt(0);
        	allProfiles[i] =cursor.getString(1);// "新生儿"+i;//cursor.getString(cursor.getColumnIndex(HETI_NAME));
        }
		
	} 
    private void addNewProfileInLevel(int level, String ProfileName, int profileId) {
		// TODO Auto-generated method stub
    	ProfileView newProfile = new ProfileView(this);
		String s=""+profileId;
		newProfile.button.setText(ProfileName);//档案名称
		newProfile.button.setId(profileId);//档案编号
		newProfile.button.setContentDescription(s);
		System.out.println("addFile:"+ProfileName+profileId);
		newProfile.button.setOnClickListener(this);
		
		if(level>=AllLevels.size()){
			addNewLevel();
		}
		AllLevels.get(level).addView(
				newProfile,//,newProfile.FileWidth,newProfile.FileHeight);
				MeasureSpec.makeMeasureSpec(newProfile.FileWidth, MeasureSpec.EXACTLY),
				MeasureSpec.makeMeasureSpec(newProfile.FileHeight, MeasureSpec.EXACTLY));

		System.out.println("addFile:"+newProfile.FileWidth+","+newProfile.FileHeight);
		setContentView(view);
		
	}
    
	public void initContentView(){

		Cursor cursor = this.managedQuery(CONTENT_URI_VIEW3,null, null, null, null);
		ProfilesSUM = cursor.getCount();
		ProfilesInOneLevel = getProfilesInOneLevel();//计算每层可以存放的档案数
        System.out.println("ProfilesInOneLevel="+ProfilesInOneLevel);
        
		allProfiles = new String[ProfilesSUM];
        
        for(int i=0;i<allProfiles.length;i++){
        	cursor.moveToNext();
        	int ID = cursor.getInt(0);
        	//HereTipa ht=new HereTipa(this);
        	//ht.selectNameAndCode(ID);
        	allProfiles[i] =cursor.getString(1);// "新生儿"+i;//cursor.getString(cursor.getColumnIndex(HETI_NAME));
        	
        	
            int selectedLevel = i / ProfilesInOneLevel;//新档案应放置的层
            System.out.println("selectedLevel="+selectedLevel);
            addNewProfileInLevel(selectedLevel,allProfiles[i],ID);
        }
	
	}
	private void createProfile() {
		// TODO Auto-generated method stub
	/*	Calendar c= Calendar.getInstance();
		String s=c.getTimeInMillis()+"";
		int pro=Integer.parseInt(s.substring(4));
		VaccinationCard vc=new VaccinationCard(getBaseContext());
		vc.setVaca_name(et_name.getText().toString());
		vc.setVaca_profile_id(pro);
		vc.setVaca_born(et_born.getText().toString());
		vc.setVaca_sex(et_sex.getText().toString());
		vc.setVaca_guardian_name(et_guardian_name.getText().toString());
		vc.setVaca_relation(et_relation.getText().toString());
		vc.setVaca_guardian_phone(et_guardian_phone.getText().toString());
		vc.setVaca_create_card_people(et_create_people.getText().toString());
		vc.setVaca_create_card_date(et_create_date.getText().toString());
		vc.insertVaccinationCard();
	*/	
		Calendar c=Calendar.getInstance();
		String s=c.getTimeInMillis()+"";
		System.out.println(s);
		//int i=Integer.MAX_VALUE;
		//System.out.println(i);
		int pro=Integer.parseInt(s.substring(4));
		System.out.println("档案编号："+pro);
		HereTipa ht=new HereTipa(getBaseContext());
		ht.setHeti_profileid(pro);
		ht.setHeti_name(et_name.getText().toString());
		ht.setHeti_here_id(et_id.getText().toString());
		ht.setHeti_now_addr(et_nowplace.getText().toString());
		ht.setHeti_hore_addr(et_hjdz.getText().toString());
		ht.setHeti_tel(et_tel.getText().toString());
		ht.setHeti_town_name(et_xzname.getText().toString());
		ht.setHeti_vico_name(et_cwhname.getText().toString());
		ht.setHeti_buil_unit(et_jddw.getText().toString());
		ht.setHeti_buil_per(et_jdr.getText().toString());
		ht.setHeti_doctor(et_doctor.getText().toString());
		ht.setHeti_buil_date(et_date.getText().toString());
		ht.insertHereTipa();
		PersonInfo pi=new PersonInfo(getBaseContext());
		pi.setPein_profile_id(pro);
		pi.insertPersonInfo();
		
		//体检表
		HealthTest htt=new HealthTest(getBaseContext());
		htt.setHete_profileid(pro);
		htt.setHete_testid(1);//第一次体检???
		htt.insertHealthTest();
		
		//住院史---限填2项
		HospitalHistory hh = new HospitalHistory(getBaseContext());
		hh.setHohi_profileid(pro);
		hh.setHohi_testid(1);
		hh.setHohi_id(1);
		hh.insertHospitalHistory();
		hh.setHohi_profileid(pro);
		hh.setHohi_testid(1);
		hh.setHohi_id(2);
		hh.insertHospitalHistory();
		//病床史---限填2项
		SickbedHistory sh = new SickbedHistory(getBaseContext());
		sh.setSihi_profileid(pro);
		sh.setSihi_testid(1);
		sh.setSihi_id(1);
		sh.insertSickbedHistory();
		sh.setSihi_profileid(pro);
		sh.setSihi_testid(1);
		sh.setSihi_id(2);
		sh.insertSickbedHistory();
		//吃药信息---限填6项
		MedicateRecord mr = new MedicateRecord(getBaseContext());
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(1);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(2);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(3);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(4);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(5);
		mr.insertMedicateRecord();
		mr.setMere_profileid(pro);
		mr.setMere_testid(1);
		mr.setMere_id(6);
		mr.insertMedicateRecord();
		//非免疫预防接种---限填3项
		NonimmuneVaccineHistory nvh = new NonimmuneVaccineHistory(getBaseContext());
		nvh.setNovh_profileid(pro);
		nvh.setNovh_testid(1);
		nvh.setNovh_id(1);
		nvh.insertNonimmuneVaccineHistory();
		nvh.setNovh_profileid(pro);
		nvh.setNovh_testid(1);
		nvh.setNovh_id(2);
		nvh.insertNonimmuneVaccineHistory();
		nvh.setNovh_profileid(pro);
		nvh.setNovh_testid(1);
		nvh.setNovh_id(3);
		nvh.insertNonimmuneVaccineHistory();
		
		ModuleSelect ms=new ModuleSelect(getBaseContext());
		ms.setMose_profile_id(pro);
		ms.setMose_health_record_id(1);
		ms.setMose_vaccinate_id(1);
		ms.insertModuleSelect();
		JieZhenRecord jzr=new JieZhenRecord(getBaseContext());
		jzr.setThre_profileid(pro);
		jzr.setThre_state(1);
		jzr.insertJieZhenRecord();
		HuiZhenRecord hzr=new HuiZhenRecord(getBaseContext());
		hzr.setCore_profileid(pro);
		hzr.setCore_state(1);
		hzr.insertHuiZhenRecord();
		
		VaccinationCard vc=new VaccinationCard(getBaseContext());
		vc.setVaca_profile_id(pro);
		vc.insertVaccinationCard();
		VaccinationRecord re=new VaccinationRecord(getBaseContext());
		re.setVare_profile_id(pro);
		re.insertVaccinationRecord();
		
		
	}

	public class myThread extends Thread{
		private Handler handler;
		private String str;
		private int state;
		public myThread(Handler handler,String str,int state){
			this.handler=handler;
			this.str=str;
			this.state=state;
		}
		public void run(){
			try{
				Looper.getMainLooper();
				sleep(200);
				Message msg=handler.obtainMessage();
				if(this.state<10){
					searchContentView(this.str,this.state);
					
					msg.what=1;
				}
				else {
					createProfile();
					searchContentView(this.str,this.state);
					msg.what=2;
				}
					handler.sendMessage(msg);
				
			}catch(Exception e){
				e.printStackTrace();
			}
			
		}
	}
	private final Handler handler =new Handler(Looper.getMainLooper()){
		public void handleMessage(Message msg){
			if(msg.what==1){
				for(int i=0;i<AllLevels.size();i++){
					AllLevels.get(i).removeAllViews();
				}
				ProfilesInOneLevel=getProfilesInOneLevel();
				if(ProfilesInOneLevel<1){
					ProfilesInOneLevel=4;
				}
				for(int i=0;i<allProfiles.length;i++){
					int selectedLevel=i/ProfilesInOneLevel; //新档案应放置的层
					addNewProfileInLevel(selectedLevel,allProfiles[i],idList[i]);
				}
				mpDialog.cancel();
			}
			else if(msg.what==2){
				ad.cancel();
    			for(int i=0;i<AllLevels.size();i++){
    				AllLevels.get(i).removeAllViews();
    			}
    			ProfilesInOneLevel = getProfilesInOneLevel();
    			if(ProfilesInOneLevel<1){
    				ProfilesInOneLevel=4;
    			}
    			for(int i=0;i<allProfiles.length;i++){
    	            int selectedLevel = i / ProfilesInOneLevel;//新档案应放置的层
    	            System.out.println("selectedLevel="+selectedLevel);
    	            addNewProfileInLevel(selectedLevel,allProfiles[i],idList[i]);
    	        }
    			mpDialog.cancel();
			}
		}
	};
	@Override
	public void onFocusChange(View arg0, boolean arg1) {
		// TODO Auto-generated method stub
		
	}
}

